<template>
  <div class="app-container">
    <div class="filter-container">

      <el-button v-has="'supplyInfoTable_add'" class="filter-item"  @click="handleCreate" type="primary" icon="el-icon-plus">新增供应商</el-button>
      <el-button v-has="'supplyInfoTable_export'" class="filter-item"  @click="handleExcelExport" type="primary" icon="el-icon-download" >{{$t('table.excelExport')}}</el-button>
      <el-button v-has="'supplyInfoTable_import'" class="filter-item" style="margin-right: 10px;" type="primary" icon="el-icon-files-excel" @click="downloadTem">{{$t('table.downloadTem')}}</el-button>
      <el-upload
        class="upload-demo"
        :action="importUrl"
        :on-success="importSuccess"
        :show-file-list="false"
        :beforeUpload="beforeAvatarUpload"
        :headers="uploadHeaders"
      >
        <el-button v-has="'supplyInfoTable_import'" class="filter-item" type="primary" icon="el-icon-upload" >{{$t('table.batchImport')}}</el-button>
      </el-upload>

      <br/>

      <el-input style="width: 200px;" class="filter-item" placeholder="供应商简称" v-model="listQuery.abbreviation">
      </el-input>

      <el-select clearable style="width: 150px" class="filter-item" v-model="listQuery.organizationType" :placeholder="$t('选择机构类别')" @change="handleFilter">
        <el-option v-for="item in $organizationTypeOptions" :key="item.key" :label="item.label" :value="item.key">
        </el-option>
      </el-select>

      <el-select clearable style="width: 150px" class="filter-item" v-model="listQuery.supplyType" :placeholder="$t('选择供应商类型')" @change="handleFilter">
        <el-option v-for="item in $supplyTypeOptions" :key="item.key" :label="item.label" :value="item.key">
        </el-option>
      </el-select>


      <el-select clearable style="width: 120px" class="filter-item" v-model="listQuery.supplyLevel" :placeholder="$t('选择评级')" @change="handleFilter">
        <el-option v-for="item in $supplyLevelOptions" :key="item.key" :label="item.label" :value="item.key">
        </el-option>
      </el-select>



      <el-select clearable style="width: 150px" class="filter-item" v-model="listQuery.status" :placeholder="$t('选择合作状态')" @change="handleFilter">
        <el-option v-for="item in $supplyStatusOptions" :key="item.key" :label="item.label" :value="item.key">
        </el-option>
      </el-select>

      <el-select clearable style="width: 150px" class="filter-item" v-model="listQuery.personId" :placeholder="$t('选择咔哒对接人')" @change="handleFilter">
        <el-option v-for="item in linkManOptions" :key="item.key" :label="item.label" :value="item.key">
        </el-option>
      </el-select>

      <br/>

      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">
        {{$t('table.search')}}
      </el-button>

      <el-button class="filter-item" type="primary" v-waves icon="el-icon-refresh" @click="restQuery">{{$t('table.reset')}}</el-button>

      <br/>


    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit
              highlight-current-row
              style="width: 100%">
      <el-table-column align="center" :label="$t('table.showId')" width="65">
        <template slot-scope="scope">
          <span>{{scope.row.supplierId}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="Logo">
        <template slot-scope="scope">
          <span>
            <img :src="scope.row.logo" width="40" height="40"/>
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="供应商简称">
        <template slot-scope="scope">
          <span>{{scope.row.abbreviation}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="机构类型">
        <template slot-scope="scope">
          <span>{{scope.row.organizationType | $organizationTypeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="供应商类型">
        <template slot-scope="scope">
          <span>{{scope.row.supplyType | $supplyTypeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="评级">
        <template slot-scope="scope">
          <span>{{scope.row.supplyLevel | $supplyLevelFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="合作状态">
        <template slot-scope="scope">
          <span>{{scope.row.status | $supplyStatusFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="对接人">
        <template slot-scope="scope">
          <span>{{scope.row.personName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作人">
        <template slot-scope="scope">
          <span>{{scope.row.operator}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="修改时间">
        <template slot-scope="scope">
          <span>{{scope.row.gmtModify | $dateConvert("YYYY-MM-DD HH:mm:ss")}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('table.actions')" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-has="'supplyInfoTable_edit'" type="primary" size="mini" @click="handleUpdate(scope.row)">{{$t('table.edit')}}</el-button>
          <el-button v-has="'supplyInfoTable_info'" type="info" size="mini" @click="handleInfo(scope.row,'info')">{{$t('table.info')}}</el-button>
          <el-button v-has="'supplyInfoTable_editLinkMans'" size="mini" class="filter-item"  @click="handleEditLinkMans(scope.row.supplierId)" type="primary">编辑联系人</el-button>
          <el-button v-has="'commTable_add'" type="info" size="mini" @click="handleComm(scope.row)">{{$t('table.communication')}}</el-button>

        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @current-change="handleCurrentChange" :current-page="page.page" :page-size="page.limit"
                     layout="total, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog title="编辑联系人" :visible.sync="dialogFormVisible" width="70%" height="40%" custom-class="linkman_dialog" top="60px" :close-on-click-modal="clickModal">
        <el-table :data="supplyLinkMans" v-loading="listLoading" border fit highlight-current-row style="width: 100%">
          <el-table-column style="width: 5%" align="center" :label="$t('table.id')">
            <template slot-scope="scope">
              <span>{{scope.$index+1}}</span>
            </template>
          </el-table-column>

          <el-table-column style="width: 20%" align="center" label="姓名">
            <template slot-scope="scope">
              <el-input v-model="supplyLinkMans[scope.$index].linkName"></el-input>
            </template>
          </el-table-column>

          <el-table-column style="width: 20%" align="center" label="手机号">
            <template slot-scope="scope">
              <el-input v-model="supplyLinkMans[scope.$index].linkMobile"></el-input>
            </template>
          </el-table-column>

          <el-table-column style="width: 20%" align="center" label="邮箱">
            <template slot-scope="scope">
              <el-input v-model="supplyLinkMans[scope.$index].linkMail"></el-input>
            </template>
          </el-table-column>

          <el-table-column style="width: 20%" align="center" label="备注">
            <template slot-scope="scope">
              <el-input v-model="supplyLinkMans[scope.$index].remark"></el-input>
            </template>
          </el-table-column>

          <el-table-column style="width: 5%" align="center" label="操作">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="handleClearLinkMan(scope.$index)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="handleSaveLinkMan">{{$t('table.save')}}</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
  import {
    fetchList,
    fetchLinkManList,
    createSupplyInfo,
    updateSupplyInfo,
    batchSaveLinkMans
  } from '@/api/supply/supplyInfo'
  import waves from '@/directive/waves' // 水波纹指令
  import { parseTime } from '@/utils'
  import { fetchSupplyLinkManList } from '@/api/communication/communication'
  import store from '@/store'

  // import {
  //   infoSupplyInfo,
  //   fetchLinkManList,
  //   createSupplyInfo,
  //   saveLinkMan,
  //   fetchSupplyLinkManList,
  //   delSupplyLinkMan
  // } from '@/api/supply/supplyInfo'

  export default {
    name: 'complexTable',
    directives: {
      waves
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: null,
        listLoading: true,
        page: {
          page: 1,
          limit: 50,
          sort: ''
        },
        listQuery: {
          supplyType: undefined,
          status: undefined,
          supplyLevel: undefined,
          personId: undefined,
          personName: undefined,
          cooperationDate: undefined,
          officialName: undefined,
          logo: undefined,
          address: undefined,
          background: undefined,
          username: undefined,
          abbreviation: undefined,
          organizationType: undefined,
          'page.limit': 50,
          'page.sort': 'SUPPLIER_ID',
          'page.order': 'DESC'
        },
        clickModal: true,
        linkManOptions: [],
        textMap: {
          update: '修改',
          create: '新增',
          info: '详情'
        },
        supplyLinkMans: [],
        rules: {
          linkName: [{ required: true, message: '用户名不能为空', trigger: 'blur' }, { min: 5, max: 16, message: '长度在5-16之间' }]
        },
        importUrl: process.env.BASE_API + '/supplierInfo/importExcel.do',
        selectIds: '',
        dialogFormVisible: false,
        focusSupplyId: ''
  
      }
    },
    filters: {

    },
    computed: {
      uploadHeaders() {
        if (store.getters.token) {
          return {
            'Authorization': store.getters.token
          }
        }
      }
    },
    created() {
      this.getList()
      this.getLinkManList()
    },
    methods: {
      getList() {
        this.listLoading = true
        fetchList(this.listQuery).then(response => {
          this.list = response.content.list
          this.total = response.content.total
          this.listLoading = false
        })
      },
      getLinkManList() {
        this.listLoading = true
        fetchLinkManList().then(response => {
          if (response.success) {
            for (var a = 0; a < response.content.length; a++) {
              var aa = { label: response.content[a].userName, key: response.content[a].id }
              this.linkManOptions.push(aa)
            }
          }
        })
      },
      // 搜索按钮
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      // 跳转页数
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.getList()
      },
      // 详情
      handleInfo(row, status) {
        const supplierId = row.supplierId
        this.$router.push({ name: 'supplyInfoInfo', query: { supplierId: supplierId, opt: status }})
      },
      resetTemp() {
        this.temp = {
          supplyType: '',
          status: '',
          supplyLevel: '',
          personId: '',
          personName: '',
          cooperationDate: '',
          officialName: '',
          logo: '',
          address: '',
          background: '',
          username: '',
          abbreviation: '',
          organizationType: ''
        }
      },
      // 打开新增页面
      handleCreate() {
        this.$router.push({ name: 'supplyInfoAdd' })
      },
      // 新增数据post
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            createSupplyInfo(this.temp).then((response) => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      // 发起沟通
      handleComm(row) {
        this.$router.push({ name: 'commAdd', query: { supplyId: row.supplierId, supplyName: row.abbreviation }})
      },
      // 更新页面
      handleUpdate(row) {
        this.$router.push({ name: 'supplyInfoEdit', query: { supplierId: row.supplierId }})
      },
      // 提交更新
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            updateSupplyInfo(tempData).then(response => {
              if (response.success) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000
                })
              }
            })
          }
        })
      },
      handleBatchImport() {
        // TODO 批量导入

      },
      handleExcelExport() {
        this.$alert('导出需要一定时间,请耐心等待', '导出提示', {
          confirmButtonText: '导出',
          callback: action => {
            if (action === 'cancel') {
              return
            }
            this.$message({
              type: 'info',
              message: '正在导出...'
            })
            var params = ''
            for (const field in this.listQuery) {
              const val = this.listQuery[field]
              if (typeof val !== 'undefined' && val !== '') {
                params += field + '=' + val + '&'
              }
            }
            if (!params.endsWith('&')) {
              // 加上token
              params += '&'
            }
            params += 'token=' + store.getters.token
            window.open(process.env.BASE_API + '/supplierInfo/exportExcel.do?' + params)
          }
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      importSuccess(response) {
        if (response.success) {
          this.$message({
            type: 'success',
            message: '导入成功'
          })
          this.getList()
        } else {
          this.$message({
            type: 'fail',
            message: response.message
          })
        }
      },
      // 上传前对文件的类型的判断
      beforeAvatarUpload(file) {
        const extension = file.name.split('.')[1] === 'xls'
        const extension2 = file.name.split('.')[1] === 'xlsx'
        if (!extension && !extension2) {
          this.$message({
            type: 'fail',
            message: '只能上传excel文件'
          })
        }
        return extension || extension2
      },
      downloadTem() {
        window.open(process.env.BASE_URL + '/供应商导入模板.xlsx')
      // window.open("http://47.96.144.33:8888/download?filename=%2Fwww%2Fwwwroot%2F%E4%BE%9B%E5%BA%94%E5%95%86%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx");
      },
      // 打开编辑联系人dialog
      handleEditLinkMans(supplyId) {
        this.getSupplyLinkManList(supplyId)
        this.dialogStatus = 'editLinkMans'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          // this.$refs['dataForm'].clearValidate()
        })
        this.focusSupplyId = supplyId
      },
      getSupplyLinkManList(supplyId) {
        fetchSupplyLinkManList(supplyId).then((response) => {
          if (response.success) {
            this.supplyLinkMans = response.content
            // 若少于5条,则添加到5条
            console.info(this.supplyLinkMans)
            const length = this.supplyLinkMans.length
            for (let i = length; i < 5; i++) {
              this.supplyLinkMans.push({})
            }
          }
        }).catch(() => {
          this.$message({
            type: 'fail',
            message: '获取失败'
          })
        })
      },
      // 清除联系人
      handleClearLinkMan(index) {
        // 二次确认
        this.$confirm('此操作将清除该联系人,点击确定会正式删除,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((response) => {
          this.supplyLinkMans.splice(index, 1)
          this.supplyLinkMans.push({})
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      restQuery() {
        this.listQuery.abbreviation = ''
        this.listQuery.organizationType = ''
        this.listQuery.supplyType = ''
        this.listQuery.supplyLevel = ''
        this.listQuery.status = ''
        this.listQuery.personId = ''
        this.getList()
      },
      handleSaveLinkMan() {
        const params = { supplyId: this.focusSupplyId, supplyLinkMans: this.supplyLinkMans }
        batchSaveLinkMans(params).then((response) => {
          if (response.success) {
            this.$message({
              type: 'success',
              message: '保存成功'
            })
            this.dialogFormVisible = false
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
          }
        }).catch(() => {
        })
      }

    }
  }
</script>